﻿using BW.Mes.WinForms.Common;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BW.Mes.WinForms.WareHouse
{
    public partial class CreateStorageLocationForm : DevExpress.XtraEditors.XtraForm
    {

        // 定义委托和事件
        public delegate void StorageLocationAddedEventHandler(object sender, EventArgs e);
        public event StorageLocationAddedEventHandler StorageLocationAdded;

        // 触发事件的方法
        protected virtual void OnStorageAdded()
        {
            StorageLocationAdded?.Invoke(this, EventArgs.Empty);
        }


        public CreateStorageLocationForm()
        {
            InitializeComponent();
            LoadWareHouseData();
            this.textEdit1.Text = "编码自动生成";
            this.textEdit1.ReadOnly = true;
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 加载货架/库区数据
        /// </summary>
        private async void LoadWareHouseData()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T3/Storagelocation/ListStorage");

                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    var jsonObject = JsonConvert.DeserializeObject<dynamic>(responseBody);

                    if (jsonObject["pageDatas"] != null)
                    {
                        // 将pageDatas转换为WareHouseItem列表
                        var dataJson = jsonObject["pageDatas"].ToString();
                        var warehouses = JsonConvert.DeserializeObject<List<Storage>>(dataJson);

                        // 假设您改用了gridLookUpEdit1控件
                        gridLookUpEdit1.Properties.DataSource = warehouses;
                        gridLookUpEdit1.Properties.DisplayMember = "StorageName";
                        gridLookUpEdit1.Properties.ValueMember = "Id";

                        // 配置下拉框，只显示仓库名称
                        gridLookUpEdit1.Properties.View.Columns.Clear();
                        gridLookUpEdit1.Properties.View.Columns.Add(
                            new DevExpress.XtraGrid.Columns.GridColumn
                            {
                                FieldName = "StorageName",
                                Caption = "货架名称",
                                Visible = true
                            }
                        );

                        // 设置默认提示文本
                        gridLookUpEdit1.Properties.NullText = "请选择货架";
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载仓库数据失败: {ex.Message}", "错误");
            }
        }

        private async void CreateStorage(object sender, EventArgs e)
        {
            var model = new Storagelocation
            {
                StorageLocationCoding = textEdit1.Text,
                StorageLocationName = textEdit2.Text,
                StorageId = (long)gridLookUpEdit1.EditValue,
                StorageLocationDescribe = textEdit3.Text,
                CreatedBy=RequestUser.InputUserName
            };
            // 调用 API 方法
            using (var client = new HttpClient())
            {
                //设置请求地址
                client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                //创建JSON数据（转换数据类型）
                var json = JsonConvert.SerializeObject(model);
                //创建请求内容
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                //发送POST请求
                var response = await client.PostAsync("T3/Storagelocation/CreateStoragelocation", content);
                //判断是否成功
                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("保存成功");
                    this.DialogResult = DialogResult.OK;
                    OnStorageAdded();
                    this.Close();
                }
                else
                {
                    XtraMessageBox.Show("保存失败:" + response.ReasonPhrase);
                }
            }
        }










        /// <summary>
        /// 货架/库区下拉
        /// </summary>
        public class Storage
        {
            public long Id { get; set; }
           
            /// <summary>
            /// 货架名称
            /// </summary>
            public string StorageName { get; set; }
         
        }

        /// <summary>
        /// 添加库区设置实体
        /// </summary>
        public class Storagelocation
        {
            /// <summary>
            /// 库位编码
            /// </summary>
            public string StorageLocationCoding { get; set; }
            /// <summary>
            /// 库位名称
            /// </summary>
            public string StorageLocationName { get; set; }
            /// <summary>
            /// 货架/库区名称
            /// </summary>
            public long StorageId { get; set; }
            /// <summary>
            /// 库位描述
            /// </summary>
            public string StorageLocationDescribe { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            public string CreatedBy { get; set; }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            CreateStorage(sender, e);
        }
    }
}